﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Configuration;
using SPLists_WS = KALE_Scanning.Sharepoint_Lists_WS;
using SPCopy_WS = KALE_Scanning.Sharepoint_Copy_WS;
using System.Reflection;
using System.IO;
using System.Net;
using System.Data.SqlClient;
using System.Drawing.Imaging;
using iTextSharp.text.pdf;
using System.Security.Principal;
using System.Collections;
using KALE_Scanning.AGC_WebServices;
using Control = KALE_Scanning.AGC_WebServices.Control;
using System.Diagnostics;

namespace KALE_Scanning
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
            pnlOCR.Hide();
            ComboLoad();
            LoadSettings();
            dynamicDotNetTwain.MaxImagesInBuffer = 1000;// Bu bize max kac sayfayı alacagımızı belirtiyor 100 temsili birsey olarak verdim scan isleminin kesilmemesi icin
            //dynamicDotNetTwain.MaxImagesInBuffer = 100;// Bu bize max kac sayfayı alacagımızı belirtiyor 100 temsili birsey olarak verdim scan isleminin kesilmemesi icin
        }

        bool bHaveScanner = false;
        string[] sdKutuphaneler;
        SP_ContentType SP_ContentType;
        SP_Field SP_Field;
        SP_Lists SP_Lists;
        #region Tarayıcı Ayarları
        private string SPROOTSITEURL = Properties.Settings.Default.SPROOTSITEURL;
        private int SCANDPI_X = 600;
        private int SCANDPI_Y = 600;
        private int SCANWIDTH = 1170;
        private int SCANHEIGHT = 1700;
        private int SCANCOLORPROFILE = 0;
        private int SCANBITDEPTH = 24;
        private bool SCANCOMBINEMOD_PDF = true;
        private bool DEBUGMODE = false;
        private List<string> ScannerSettingsList = new List<string>();
        #endregion

        #region Yeni Form Ayarları

        private List<string> lookUpFieldInfo = new List<string>();
        //private string outgoingSourceItemId = string.Empty;
        private int lookUpCounter = 0;
        private string relativeLibraryName = string.Empty;
        private string uploadMsg = string.Empty;
        private int counter = 1;
        private List<SP_Field> copyFields = new List<SP_Field>();
        private List<System.Windows.Forms.Control> controlsNameList = new List<System.Windows.Forms.Control>();

        #endregion


        #region newWebService Sezgin
        AGC_WebServices.Department[] oDepartments;
        string sAdres = "";
        string sLibraryName = "";
        string sContentTypeID = "";
        AGC_WebServices.Control[] oFields;
        UploadType upType;
        List<byte[]> documentsByteList = new List<byte[]>();
        string sFileSourcePath = "";
        Hashtable lookupValues = new Hashtable();
        string siteUrl = "";
        #endregion

        private void FrmMainLoad(object sender, EventArgs e)
        {
            if (!bHaveScanner)
            {
                MessageBox.Show("Sisteminizde scanner bulunamadı. Lütfen ilgili kişi ile irtibata geçiniz!", "Hata!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Application.Exit();
            }
            else
            {
                dynamicDotNetTwain.OpenSource();
                dynamicDotNetTwain.IfDisableSourceAfterAcquire = true;
                dynamicDotNetTwain.UseWaitCursor = false;
                
            }
            #region Ayarlar icin

            List<string> a = new List<string>();
            a = ConfigurationSettings.AppSettings.AllKeys.ToList();

            for (int i = 0; i < a.Count; i++)
            {
                ListViewItem lvi = new ListViewItem();
                ListViewItem.ListViewSubItem lvsi = new ListViewItem.ListViewSubItem();
                lvi.Text = Crypt.Decrypt(a[i].ToString());
                lvsi.Text = Crypt.Decrypt(ConfigurationSettings.AppSettings.Get(a[i].ToString()));
                lvi.SubItems.Add(lvsi);
                lsvAppConfig.Items.Add(lvi);
            }

            #endregion
            string[] sunucular = Crypt.Decrypt(ConfigurationSettings.AppSettings.Get(Crypt.Encrypt("Sunucu"))).ToString().Split('|');
            foreach (string item in sunucular)
            {
                cmbSunucu.Items.Add(item);
            }
            try
            {
                if (cmbSunucu.Items.Count != 0)
                {
                    cmbSunucu.SelectedIndex = 0;
                }
                txtKullanici.Text = UserProperty.UserProperties.UserName;// @"CALIKSOA\srv-hld-spsfa";//WindowsIdentity.GetCurrent().Name;
                txtEtkiAlani.Text = UserProperty.UserProperties.Domain;
                txtSifre.Text = UserProperty.UserProperties.Password;

            }
            catch (Exception ex)
            {
                MessageBox.Show("Hata olustu!-" + ex.Message + " - " + ex.StackTrace);
            }
        }

        private void CmbSunucuSelectedIndexChanged(object sender, EventArgs e)
        {
            cmbDepartman.Items.Clear();
            cmbKutuphane.Items.Clear();
            cmbIcerikTip.Items.Clear();
            grpBoxControls.Controls.Clear();
            try
            {
                using (AGC_WebServices.Service ws = new AGC_WebServices.Service())
                {

                    //ws.UseDefaultCredentials = true;
                    ws.Credentials = UserProperty.UserProperties.Credential;
                    oDepartments = ws.findLibraryOfGroupUser(@"CALIKSOA\srv-hld-spsfa", cmbSunucu.SelectedItem.ToString());
                    if (oDepartments == null)
                    {
                        MessageBox.Show("Kullanıcı İsmi veya izinleri ile alakalı bir sorun olustu.");
                        return;
                    }
                    else
                    {
                        foreach (Department item in oDepartments)
                        {
                            cmbDepartman.Items.Add(item);
                        }
                        cmbDepartman.ValueMember = "SiteID";
                        cmbDepartman.DisplayMember = "SiteName";
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Hata Olustu!--" + ex.Message + " - " + ex.StackTrace);
            }
            if (cmbDepartman.Items.Count != 0)
            {
                cmbDepartman.SelectedIndex = 0;
            }
        }

        private void CmbDepartmanSelectedIndexChanged(object sender, EventArgs e)
        {
            //if (cmbDepartman.SelectedIndex == 0)
            //    return;
            cmbKutuphane.Items.Clear();
            cmbIcerikTip.Items.Clear();
            try
            {
                AGC_WebServices.Department dep = (cmbDepartman.SelectedItem as AGC_WebServices.Department);
                if (dep != null && dep.Libraries != null && dep.Libraries.Length > 0)
                {
                    cmbKutuphane.Items.Insert(0, Utility.GetNullLib());
                    foreach (Library item in dep.Libraries)
                    {
                        cmbKutuphane.Items.Add(item);
                    }
                    cmbKutuphane.ValueMember = "SubSiteName";
                    cmbKutuphane.DisplayMember = "LibName";
                    cmbKutuphane.SelectedIndex = 0;
                    btnTaraGonder.Enabled = false;
                }
                else
                {
                    MessageBox.Show("Departman verilerinde bir hata oluştu");
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Deparman verilerinde hata oluştu! Message : \n" + ex.Message + Environment.NewLine + "Source : \n" + ex.StackTrace, "Hata!");
                return;
            }
        }

        private void CmbKutuphaneSelectedIndexChanged(object sender, EventArgs e)
        {
            cmbIcerikTip.Items.Clear();
            if (cmbKutuphane.SelectedIndex == 0)
                return;

            try
            {
                AGC_WebServices.Library lib = (cmbKutuphane.SelectedItem as AGC_WebServices.Library);
                if (lib != null && lib.ContentTypes != null && lib.ContentTypes.Length > 0)
                {
                    cmbIcerikTip.Items.Insert(0, Utility.GetNullContentType());
                    foreach (ContentType item in lib.ContentTypes)
                    {
                        cmbIcerikTip.Items.Add(item);
                    }
                    cmbIcerikTip.ValueMember = "ContentTypeID";
                    cmbIcerikTip.DisplayMember = "Name";
                    cmbIcerikTip.SelectedIndex = 0;
                }
                else
                {
                    MessageBox.Show("Kütüphane verilerinde bir hata oluştu");
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Kütüphane verilerinde hata oluştu! Message : \n" + ex.Message + Environment.NewLine + "Source : \n" + ex.StackTrace, "Hata!");
                return;
            }
        }

        private void CmbIcerikTipSelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbIcerikTip.SelectedIndex == 0)
                return;
            controlsNameList.Clear();
            lookupValues.Clear();
            grpBoxControls.Controls.Clear();
            counter = 0;

            try
            {
                AGC_WebServices.ContentType CType = (cmbIcerikTip.SelectedItem as AGC_WebServices.ContentType);
                if (CType != null)
                {
                    sAdres = Utility.CheckLastSlash(cmbSunucu.SelectedItem.ToString()) + (cmbDepartman.SelectedItem as Department).SiteUrl;
                    siteUrl = Utility.CheckLastSlash(cmbSunucu.SelectedItem.ToString());
                    sLibraryName = (cmbKutuphane.SelectedItem as Library).LibName;
                    sContentTypeID = (cmbIcerikTip.SelectedItem as ContentType).ContentTypeID;
                    oFields = Methods.GetFields(sAdres, sLibraryName, sContentTypeID);

                    LookupFieldValue[] lookupBrim = null;
                    System.Windows.Forms.Control ctrl = null;
                    foreach (Control field in oFields)
                    {
                        Methods.Site = siteUrl;
                        ctrl = Methods.CreateDynamicControl(field, ref this.grpBoxControls, sAdres, ref counter, out lookupBrim, sLibraryName);

                        if (lookupBrim != null)
                        {
                            lookupValues.Add(ctrl.Name, lookupBrim);
                        }
                        controlsNameList.Add(ctrl);
                    }
                    btnTaraGonder.Enabled = true;
                    btnBrowse.Enabled = true;
                }
                else
                {
                    MessageBox.Show("İçerik Tipi verilerinde hata oluştu!");
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("İçerik tipi verilerinde hata oluştu! Message : \n" + ex.Message + Environment.NewLine + "Source : \n" + ex.StackTrace, "Hata!");
                return;
            }

        }

        #region XML Sifreleme method ları
        private string Sifrele(string clear)
        {
            //Xml Dosyasındaki bilgilerin gizliliği için şifreleme sağlar

            int lenght = clear.Length;
            char[] a = clear.ToCharArray();
            for (int i = 0; i < lenght; i++)
            {
                a[i] = Convert.ToChar(Convert.ToInt32(a[i]) + 13);
            }
            clear = "";
            for (int i = 0; i < lenght; i++)
            {
                clear += a[i].ToString();
            }
            return clear;
        }

        public string Coz(string bad)
        {
            //Xml Dosyasındaki bilgilerin program tarafından anlaşılabilir olmasını sağlar

            int lenghtt = bad.Length;
            char[] a = bad.ToCharArray();
            for (int i = 0; i < lenghtt; i++)
            {
                a[i] = Convert.ToChar(Convert.ToInt32(a[i]) - 13);
            }
            bad = "";
            for (int i = 0; i < lenghtt; i++)
            {
                bad += a[i].ToString();
            }
            return bad;
        }
        #endregion

        #region for User Info

        private void BtnKullaniciBilgiKayitClick(object sender, EventArgs e)
        {
            //load the xml Document
            XmlDocument xmlDocread = new XmlDocument();
            xmlDocread.Load(Application.StartupPath + "\\scanUpload.xml");
            //new xml Document
            XmlDocument xmlDoc = new XmlDocument();

            if (!chbVarsayilanKullanici.Checked)
            {
                if (chbBilgiKayit.Checked)
                {

                    // Write down the XML declaration
                    XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);

                    // Create the root element
                    XmlElement rootNode = xmlDoc.CreateElement("ScanUpload");
                    xmlDoc.InsertBefore(xmlDeclaration, xmlDoc.DocumentElement);
                    xmlDoc.AppendChild(rootNode);

                    // Create a new element and add it to the root node
                    XmlElement parentNode = xmlDoc.CreateElement("Information");

                    // Set attribute name and value!
                    parentNode.SetAttribute("Url", xmlDocread.DocumentElement["Information"].Attributes["Url"].Value);
                    xmlDoc.DocumentElement.PrependChild(parentNode);

                    // Create a new element and add it to the root node
                    parentNode = xmlDoc.CreateElement("Credential");

                    // Set attributes name and value!
                    parentNode.SetAttribute("Exist", chbBilgiKayit.Checked.ToString());
                    xmlDoc.DocumentElement.PrependChild(parentNode);
                    parentNode.SetAttribute("UserName", Sifrele(txtKullanici.Text));
                    xmlDoc.DocumentElement.PrependChild(parentNode);
                    parentNode.SetAttribute("Password", Sifrele(txtSifre.Text));
                    xmlDoc.DocumentElement.PrependChild(parentNode);
                    parentNode.SetAttribute("Domain", Sifrele(txtEtkiAlani.Text));
                    xmlDoc.DocumentElement.PrependChild(parentNode);

                    // Save to the XML file
                    xmlDoc.Save(Application.StartupPath + "\\scanUpload.xml");
                }
                else
                {

                    // Write down the XML declaration
                    XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);

                    // Create the root element
                    XmlElement rootNode = xmlDoc.CreateElement("ScanUpload");
                    xmlDoc.InsertBefore(xmlDeclaration, xmlDoc.DocumentElement);
                    xmlDoc.AppendChild(rootNode);

                    // Create a new element and add it to the root node
                    XmlElement parentNode = xmlDoc.CreateElement("Information");

                    // Set attribute name and value!
                    parentNode.SetAttribute("Url", xmlDocread.DocumentElement["Information"].Attributes["Url"].Value);
                    xmlDoc.DocumentElement.PrependChild(parentNode);

                    // Create a new element and add it to the root node
                    parentNode = xmlDoc.CreateElement("Credential");

                    // Set attributes name and value!
                    parentNode.SetAttribute("Exist", chbBilgiKayit.Checked.ToString());
                    xmlDoc.DocumentElement.PrependChild(parentNode);
                    parentNode.SetAttribute("UserName", xmlDocread.DocumentElement["Credential"].Attributes["UserName"].Value);
                    xmlDoc.DocumentElement.PrependChild(parentNode);
                    parentNode.SetAttribute("Password", xmlDocread.DocumentElement["Credential"].Attributes["Password"].Value);
                    xmlDoc.DocumentElement.PrependChild(parentNode);
                    parentNode.SetAttribute("Domain", xmlDocread.DocumentElement["Credential"].Attributes["Domain"].Value);
                    xmlDoc.DocumentElement.PrependChild(parentNode);

                    // Save to the XML file
                    xmlDoc.Save(Application.StartupPath + "\\scanUpload.xml");
                }
            }
            else
            {

                // Write down the XML declaration
                XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);

                // Create the root element
                XmlElement rootNode = xmlDoc.CreateElement("ScanUpload");
                xmlDoc.InsertBefore(xmlDeclaration, xmlDoc.DocumentElement);
                xmlDoc.AppendChild(rootNode);

                // Create a new element and add it to the root node
                XmlElement parentNode = xmlDoc.CreateElement("Information");

                // Set attribute name and value!
                parentNode.SetAttribute("Url", xmlDocread.DocumentElement["Information"].Attributes["Url"].Value);
                xmlDoc.DocumentElement.PrependChild(parentNode);

                // Create a new element and add it to the root node
                parentNode = xmlDoc.CreateElement("Credential");

                // Set attributes name and value!
                parentNode.SetAttribute("Exist", "False");
                xmlDoc.DocumentElement.PrependChild(parentNode);
                parentNode.SetAttribute("UserName", xmlDocread.DocumentElement["Credential"].Attributes["UserName"].Value);
                xmlDoc.DocumentElement.PrependChild(parentNode);
                parentNode.SetAttribute("Password", xmlDocread.DocumentElement["Credential"].Attributes["Password"].Value);
                xmlDoc.DocumentElement.PrependChild(parentNode);
                parentNode.SetAttribute("Domain", xmlDocread.DocumentElement["Credential"].Attributes["Domain"].Value);
                xmlDoc.DocumentElement.PrependChild(parentNode);

                // Save to the XML file
                xmlDoc.Save(Application.StartupPath + "\\scanUpload.xml");
            }
            tabControlArsiv.SelectedIndex = 0;
        }

        private void ChbVarsayilanKullaniciCheckedChanged(object sender, EventArgs e)
        {
            if (chbVarsayilanKullanici.Checked)
            {
                chbBilgiKayit.Enabled = false;
                chbBilgiKayit.Checked = false;
                txtKullanici.Enabled = false;
                txtKullanici.Text = "";
                txtSifre.Enabled = false;
                txtSifre.Text = "";
                txtEtkiAlani.Enabled = false;
                txtEtkiAlani.Text = "";
            }
            else
            {
                txtKullanici.Enabled = true;
                txtSifre.Enabled = true;
                txtEtkiAlani.Enabled = true;
                chbBilgiKayit.Enabled = true;
            }
        }

        private void ChbBilgiKayitCheckedChanged(object sender, EventArgs e)
        {
            if (chbBilgiKayit.Checked) { chbVarsayilanKullanici.Checked = false; }
        }

        public string GetUserName()
        {
            return txtKullanici.Text;
        }
        public string GetPassword()
        {
            return txtSifre.Text;
        }
        public string GetDomain()
        {
            return txtEtkiAlani.Text;
        }
        public bool WasSaved()
        {
            return chbBilgiKayit.Checked;
        }
        public bool Wasdefault()
        {
            return chbVarsayilanKullanici.Checked;
        }

        #endregion

        #region Liste Getiren Fonks
        public List<SP_Lists> GetListListsByWs(string wsAdresi)
        {
            Sharepoint_Lists_WS.Lists listsWs = new Sharepoint_Lists_WS.Lists();
            List<SP_Lists> listeler = new List<SP_Lists>();
            listsWs.Url = wsAdresi + "/_vti_bin/lists.asmx";
            listsWs.Credentials = CredentialCache.DefaultCredentials;

            try
            {
                listeler = ReadXML_Lists(listsWs.GetListCollection().OuterXml);
            }
            catch
            {
                listeler = null;
            }

            return listeler;
        }

        private List<SP_Lists> ReadXML_Lists(string xmlVeri)
        {
            List<SP_Lists> listeler = new List<SP_Lists>();

            try
            {
                XmlDocument xml = new XmlDocument();
                xml.LoadXml(xmlVeri);
                XmlNodeList xmlListeler = xml.GetElementsByTagName("List");

                foreach (XmlNode xmlListe in xmlListeler)
                {
                    SP_Lists liste = new SP_Lists();

                    foreach (XmlAttribute oznitelik in xmlListe.Attributes)
                    {
                        try
                        {
                            PropertyInfo listeOzellik = typeof(SP_Lists).GetProperty(oznitelik.Name);
                            listeOzellik.SetValue(liste, oznitelik.Value, null);
                        }
                        catch (Exception ex)
                        {
                            // MessageBox.Show(ex.Message, "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    if (liste.Title != "Paylaşılan Belgeler" && liste.Title != "Site Varlıkları" && liste.Title != "Site Sayfaları")
                    {
                        listeler.Add(liste);
                    }
                }
                return listeler;
            }
            catch (Exception ex)
            {
                listeler = null;
                return listeler;
            }
        }
        #endregion

        #region İlgili Content Type a ait Custom Field lar
        public List<SP_Field> GetFieldsforContentType(string wsAddress, string listName, string contentTypeId)
        {
            List<SP_Field> myFieldsforContentType = new List<SP_Field>();
            SPLists_WS.Lists listsWs = new SPLists_WS.Lists();
            listsWs.Url = Utility.CheckLastSlash(wsAddress) + "_vti_bin/lists.asmx";
            listsWs.Credentials = CredentialCache.DefaultCredentials;
            try
            {
                myFieldsforContentType = ReadXmlFields(listsWs.GetListContentType(listName, contentTypeId).OuterXml);
            }
            catch (Exception ex)
            {

                throw ex;
            }
            return myFieldsforContentType;
        }

        private List<SP_Field> ReadXmlFields(string XMLData)
        {
            List<SP_Field> listFields = new List<SP_Field>();

            try
            {
                XmlDocument xml = new XmlDocument();
                xml.LoadXml(XMLData);
                XmlNodeList xmlContentType = xml.GetElementsByTagName("ContentType");
                XmlNodeList xmlContentTypeFieldlar = xml.GetElementsByTagName("Field");

                foreach (XmlNode xmlAltDugum in xml.ChildNodes)
                {
                    if (xmlAltDugum.Name.ToLower() == "contenttype")
                    {
                        foreach (XmlNode xmlListEleman in xmlAltDugum.ChildNodes)
                        {
                            if (xmlListEleman.Name.ToLower() == "fields")
                            {
                                foreach (XmlNode xmlField in xmlListEleman.ChildNodes)
                                {
                                    if (xmlField.Name.ToLower() == "field")
                                    {
                                        SP_Field = new SP_Field();
                                        foreach (XmlAttribute attribute in xmlField.Attributes)
                                        {
                                            try
                                            {
                                                PropertyInfo fieldProperties = typeof(SP_Field).GetProperty(attribute.Name);
                                                fieldProperties.SetValue(SP_Field, attribute.Value, null);
                                            }
                                            catch (Exception ex)
                                            {
                                                // MessageBox.Show(ex.Message, "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                            }
                                        }
                                        listFields.Add(SP_Field);
                                    }
                                }
                            }
                        }
                    }
                }
                return listFields;
            }
            catch (Exception ex)
            {
                listFields = null;
                return listFields;
            }
        }
        #endregion

        #region İlgili Library alanları (Muhasebe) KULLANILMIYOR
        public List<SP_Field> GetFieldsforLibrary(string wsAddress, string listName, string contentTypeId)
        {
            List<SP_Field> myFieldsforContentType = new List<SP_Field>();
            SPLists_WS.Lists listsWs = new SPLists_WS.Lists();
            listsWs.Url = cmbSunucu.SelectedItem.ToString() + "/_vti_bin/lists.asmx";
            listsWs.Credentials = CredentialCache.DefaultCredentials;
            try
            {
                myFieldsforContentType = ReadXmlLibraryFields(listsWs.GetList(listName).OuterXml);
            }
            catch (Exception)
            {

                throw;
            }
            return myFieldsforContentType;
        }

        private List<SP_Field> ReadXmlLibraryFields(string XMLData)
        {
            List<SP_Field> listFields = new List<SP_Field>();

            try
            {
                XmlDocument xml = new XmlDocument();
                xml.LoadXml(XMLData);
                XmlNodeList xmlFieldlar = xml.GetElementsByTagName("Field");
                foreach (XmlNode xmlField in xmlFieldlar)
                {
                    if (xmlField.Name.ToLower() == "field")
                    {
                        SP_Field = new SP_Field();
                        foreach (XmlAttribute attribute in xmlField.Attributes)
                        {
                            try
                            {
                                PropertyInfo fieldProperties = typeof(SP_Field).GetProperty(attribute.Name);
                                fieldProperties.SetValue(SP_Field, attribute.Value, null);
                            }
                            catch (Exception ex)
                            {
                                // MessageBox.Show(ex.Message, "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                        listFields.Add(SP_Field);
                    }
                }
                return listFields;
            }
            catch (Exception ex)
            {
                listFields = null;
                return listFields;
            }
        }
        #endregion




        #region Choice field elemanlarının alınması
        public List<string> GetChoicesFieldElements(string _WSAdresi, string _ListName, string _ContentTypeID, string _FieldID)
        {
            List<string> myChoiceFields = new List<string>();
            SPLists_WS.Lists Lists_WS = new SPLists_WS.Lists();
            Lists_WS.Url = Utility.CheckLastSlash(sAdres) + "_vti_bin/lists.asmx";
            Lists_WS.Credentials = System.Net.CredentialCache.DefaultCredentials;
            try
            {
                myChoiceFields = ReadXML_FieldsChoices(Lists_WS.GetListContentType(_ListName, _ContentTypeID).OuterXml, _FieldID);
            }
            catch (Exception ex)
            {
                MessageBox.Show(_ListName + " elemanları alınamıyor!\n Message : \n:" + ex.Message + "\nSource : \n" + ex.StackTrace);
            }
            return myChoiceFields;
        }

        private List<string> ReadXML_FieldsChoices(string XMLData, string FieldID)
        {
            List<string> List_Choices = new List<string>();

            try
            {
                XmlDocument XML = new XmlDocument();
                XML.LoadXml(XMLData);
                XmlNodeList XML_ContentType = XML.GetElementsByTagName("ContentType");
                XmlNodeList XML_ContentTypeFieldlar = XML.GetElementsByTagName("Field");

                foreach (XmlNode XML_AltDugum in XML.ChildNodes)
                {
                    if (XML_AltDugum.Name.ToLower() == "contenttype")
                    {
                        foreach (XmlNode XML_ListEleman in XML_AltDugum.ChildNodes)
                        {
                            if (XML_ListEleman.Name.ToLower() == "fields")
                            {
                                foreach (XmlNode XML_Field in XML_ListEleman.ChildNodes)
                                {
                                    if (XML_Field.Name.ToLower() == "field")
                                    {
                                        if (XML_Field.Attributes["ID"].Value == FieldID)
                                        {
                                            foreach (XmlNode XML_FieldChoices in XML_Field.ChildNodes)
                                            {
                                                if (XML_FieldChoices.Name.ToLower(System.Globalization.CultureInfo.GetCultureInfoByIetfLanguageTag("en")) == "choices" || XML_FieldChoices.Name.ToLower() == "choıces")
                                                {
                                                    foreach (XmlNode XML_FieldChoice in XML_FieldChoices.ChildNodes)
                                                    {
                                                        if (XML_FieldChoice.Name.ToLower(System.Globalization.CultureInfo.GetCultureInfoByIetfLanguageTag("en")) == "choice" || XML_FieldChoice.Name.ToLower() == "choıce")
                                                        {
                                                            string List = "";
                                                            try
                                                            {
                                                                List = XML_FieldChoice.InnerText;

                                                                List_Choices.Add(List);
                                                            }
                                                            catch (Exception ex)
                                                            {
                                                                // MessageBox.Show(ex.Message, "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                return List_Choices;
            }
            catch (Exception ex)
            {
                List_Choices = null;
                return List_Choices;
            }
        }

        private void btnTaraGonder_Click(object sender, EventArgs e)
        {
            dynamicDotNetTwain.UseWaitCursor = true;
            upType = UploadType.Scanner;

            btnBrowse.Enabled = false;
            dynamicDotNetTwain.IfAppendImage = true;
            
            dynamicDotNetTwain.AcquireImage();


            //bool controlKey = true;
            //foreach (System.Windows.Forms.Control control in grpBoxControls.Controls)
            //{
            //    control.Focus();
            //    if (!Validate())
            //    {
            //        DialogResult = DialogResult.None;
            //        MessageBox.Show("Lütfen Gerekli Alanları Doldurunuz!");
            //        controlKey = false;
            //        return;
            //    }
            //}
            //if (controlKey == true)
            //{
            //}
        }
        #endregion

        #region Yeni Scan funcs

        #endregion

        #region FisNo Upload





        private void CreateColumn(string listName, string type, string columnName, string DisplayName, string Description)
        {
            //dokumanı yüklediğimiz kütüphanede, gönderdiğimiz metadatalar için sütun olup olmadığını
            //kontrol ediyor eğer yoksa ilgili sütünu oluşturuyor
            if (Description == "") Description = "Description";
            SPLists_WS.Lists ListService = new SPLists_WS.Lists();
            //if (useDefaultCredential) listService.Credentials = System.Net.CredentialCache.DefaultCredentials;
            //else { listService.Credentials = new NetworkCredential(userInfo[0], userInfo[1], userInfo[2]); }
            string surl;
            if (cmbSunucu.SelectedItem.ToString().EndsWith("/")) surl = cmbSunucu.SelectedItem.ToString();
            else surl = cmbSunucu.SelectedItem.ToString() + "/";
            ListService.Url = surl + "_vti_bin/Lists.asmx";
            ListService.Credentials = System.Net.CredentialCache.DefaultCredentials;

            XmlNode ndList = ListService.GetList(listName);
            //if()

            bool durum = false;
            XmlNode a = ndList.ChildNodes[0];
            foreach (XmlNode b in a)
            {
                if (b.Attributes["DisplayName"].Value == DisplayName)
                {
                    durum = true;
                }
            }
            if (durum == false)
            {
                XmlNode ndVersion = ndList.Attributes["Version"];

                XmlDocument xmlDoc = new System.Xml.XmlDocument();

                XmlNode ndDeleteFields = xmlDoc.CreateNode(XmlNodeType.Element, "Fields", "");
                XmlNode ndProperties = xmlDoc.CreateNode(XmlNodeType.Element, "List", "");
                XmlAttribute ndTitleAttrib = (XmlAttribute)xmlDoc.CreateNode(XmlNodeType.Attribute, "Title", "");
                XmlAttribute ndDescriptionAttrib = (XmlAttribute)xmlDoc.CreateNode(XmlNodeType.Attribute, "Description", "");
                XmlNode ndNewFields = xmlDoc.CreateNode(XmlNodeType.Element, "Fields", "");

                XmlNode ndUpdateFields = xmlDoc.CreateNode(XmlNodeType.Element, "Fields", "");

                ndTitleAttrib.Value = ndList.Attributes["Title"].Value;
                ndDescriptionAttrib.Value = ndList.Attributes["Description"].Value; ;

                ndProperties.Attributes.Append(ndTitleAttrib);
                ndProperties.Attributes.Append(ndDescriptionAttrib);

                ndDeleteFields.InnerXml = "";
                //"<Method ID='5'><Field Name='Field1'/></Method>" +
                //"<Method ID='6'><Field Name='Field2'/></Method>";

                if (type != "Number")
                {
                    ndNewFields.InnerXml = "<Method ID='1' AddToView=''><Field Type='" + type + "' Name='" + columnName +
                        "' DisplayName='" + DisplayName + "' Description='" + Description + "'/></Method>";
                }
                else if (type == "Number")
                {
                    //Decimals="0"
                    ndNewFields.InnerXml = "<Method ID='1' AddToView=''><Field Type='" + type + "' Name='" + columnName +
                    "' DisplayName='" + DisplayName + "' Description='" + Description + "' Decimals='2'/></Method>";
                }

                //FromBaseType='TRUE'
                ndUpdateFields.InnerXml = "";//"<Method ID='4'><Field Type='Text' Name='" + columnName.Replace(" ","") +
                //"' DisplayName='"+columnName+"'Required='TRUE' FromBaseType='TRUE' Description='Description'/></Method>";

                try
                {
                    XmlNode ndReturn =
                       ListService.UpdateList(listName,
                       ndProperties, ndNewFields, null, null,
                       ndVersion.Value);

                    lblInfo.Text = DisplayName + " öğesi için alan oluşturuluyor";
                    //MessageBox.Show(ndReturn.OuterXml);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Message:\n" + ex.Message + "\nStackTrace:\n" + ex.StackTrace);
                }
            }
        }
        #endregion

        #region Upload Content Type Library
        public bool uploadDocument(AGC_WebServices.Control[] _IncomingFields)
        {
            List<Sharepoint_Copy_WS.FieldInformation> incomingFieldInfo = new List<Sharepoint_Copy_WS.FieldInformation>();
            bool onay = false;
            string KutuphaneSon = string.Empty;
            KutuphaneSon = RcharDetect(sLibraryName);
            try
            {
                string webUrl = Utility.CheckLastSlash(sAdres);

                Sharepoint_Copy_WS.Copy copyService = new Sharepoint_Copy_WS.Copy();
                copyService.Url = webUrl + "_vti_bin/copy.asmx";


                copyService.Credentials = System.Net.CredentialCache.DefaultCredentials;
                copyService.Credentials = UserProperty.UserProperties.Credential;

                string sourceUrl = sFileSourcePath;
                FileInfo fileInf = new FileInfo(sFileSourcePath);
                string[] destinationUrl = { webUrl + KutuphaneSon + "/" + fileInf.Name };

                Sharepoint_Copy_WS.CopyResult cResult1 = new Sharepoint_Copy_WS.CopyResult();
                Sharepoint_Copy_WS.CopyResult cResult2 = new Sharepoint_Copy_WS.CopyResult();
                Sharepoint_Copy_WS.CopyResult[] cResultArray = { cResult1, cResult2 };

                incomingFieldInfo = Methods.CreateDynamicCopyField(_IncomingFields, ref lookupValues, ref controlsNameList);

                Sharepoint_Copy_WS.FieldInformation[] fFieldInfoArray = new Sharepoint_Copy_WS.FieldInformation[incomingFieldInfo.Count];
                for (int i = 0; i < incomingFieldInfo.Count; i++)
                {
                    SPCopy_WS.FieldInformation _fInfo = incomingFieldInfo[i];
                    fFieldInfoArray[i] = _fInfo;
                }
                FileStream strm = new FileStream(sourceUrl, FileMode.Open, FileAccess.Read);
                byte[] fileContents = new Byte[strm.Length];
                int ia = strm.Read(fileContents, 0, Convert.ToInt32(strm.Length));
                strm.Close();

                uint copyresult = copyService.CopyIntoItems(sourceUrl, destinationUrl, fFieldInfoArray, fileContents, out cResultArray);

                //File.Delete(sFileSourcePath + "\\" + pdfSonTwain);
                uploadMsg = "Döküman yüklemesi başarılı bir şekilde tamamlandı...";
                btnTaraGonder.Enabled = true;
                this.Cursor = Cursors.Default;
                this.Enabled = true;
                onay = true;
                relativeLibraryName = "";
            }
            catch (Exception ex)
            {
                this.Enabled = true;
                uploadMsg = "Dokuman yukleme islemi sırasında bir hata olustu!!";
                //File.Delete(Application.StartupPath + "\\" + pdfSonTwain);
                this.Cursor = Cursors.Default;
            }
            return onay;
        }

        //public List<Sharepoint_Copy_WS.FieldInformation> create_DynamicCopyField(AGC_WebServices.Control[] _FieldClass) {
        //    List<Sharepoint_Copy_WS.FieldInformation> abc = new List<Sharepoint_Copy_WS.FieldInformation>();

        //    int count = 0;
        //    foreach (AGC_WebServices.Control item in _FieldClass) {
        //        if (controlsNameList[count] is TextBox) {
        //            Sharepoint_Copy_WS.FieldInformation newFieldText = new Sharepoint_Copy_WS.FieldInformation();
        //            newFieldText.InternalName = item.StaticName;
        //            newFieldText.DisplayName = item.Isim;
        //            newFieldText.Type = Sharepoint_Copy_WS.FieldType.Text;
        //            newFieldText.Value = controlsNameList[count].Text;
        //            abc.Add(newFieldText);
        //            count++;
        //            #region switch
        //            //switch (item.Type) {                               
        //            //    case "Text":      
        //            //        Sharepoint_Copy_WS.FieldInformation newFieldText = new Sharepoint_Copy_WS.FieldInformation();
        //            //        newFieldText.DisplayName = item.DisplayName;
        //            //        newFieldText.Type = Sharepoint_Copy_WS.FieldType.Text;
        //            //        newFieldText.Value = cItem.Text;
        //            //        abc.Add(newFieldText);
        //            //        break;
        //            //    case "Date":
        //            //        Sharepoint_Copy_WS.FieldInformation newFieldDate = new Sharepoint_Copy_WS.FieldInformation();
        //            //        newFieldDate.DisplayName = item.DisplayName;
        //            //        newFieldDate.Type = Sharepoint_Copy_WS.FieldType.DateTime;
        //            //        newFieldDate.Value = cItem.Text;
        //            //        abc.Add(newFieldDate);
        //            //        break;
        //            //    case "Choice":
        //            //        Sharepoint_Copy_WS.FieldInformation newFieldChoice = new Sharepoint_Copy_WS.FieldInformation();
        //            //        newFieldChoice.DisplayName = item.DisplayName;
        //            //        newFieldChoice.Type = Sharepoint_Copy_WS.FieldType.DateTime;
        //            //        newFieldChoice.Value = cItem.Text;
        //            //        abc.Add(newFieldChoice);
        //            //        break;
        //            //    case "Boolean":
        //            //        Sharepoint_Copy_WS.FieldInformation newFieldBoolean = new Sharepoint_Copy_WS.FieldInformation();
        //            //        newFieldBoolean.DisplayName = item.DisplayName;
        //            //        newFieldBoolean.Type = Sharepoint_Copy_WS.FieldType.DateTime;
        //            //        newFieldBoolean.Value = cItem.Text;
        //            //        abc.Add(newFieldBoolean);
        //            //        break;
        //            //    default:
        //            //        break;
        //            //} 
        //            #endregion
        //        }
        //        else if (controlsNameList[count] is ComboBox) {
        //            if(item.Type == "Lookup"){
        //                Sharepoint_Copy_WS.FieldInformation newFieldChoice = new Sharepoint_Copy_WS.FieldInformation();
        //                newFieldChoice.InternalName = item.StaticName;
        //                newFieldChoice.DisplayName = item.Isim;
        //                newFieldChoice.Type = Sharepoint_Copy_WS.FieldType.Choice;
        //                newFieldChoice.Value = "";
        //                ComboBox cmb = controlsNameList[count] as ComboBox;
        //                if(cmb.SelectedItem != null && (cmb.SelectedItem as LookupFieldValue).Value != string.Empty)
        //                {
        //                    lstMultiLineControl.Add(item);

        //                    AGC_WebServices.LookupFieldValue[] fieldArr = new LookupFieldValue[1];
        //                    fieldArr[0] = cmb.SelectedItem as LookupFieldValue;

        //                    lstLookupFieldValues.Add(fieldArr);
        //                }
        //                else
        //                {
        //                    newFieldChoice.Value = controlsNameList[count].Text;
        //                }
        //                abc.Add(newFieldChoice);

        //                count++;
        //            }
        //            else if(item.Type == "Choice")
        //            {
        //                Sharepoint_Copy_WS.FieldInformation newFieldChoice = new Sharepoint_Copy_WS.FieldInformation();
        //                newFieldChoice.InternalName = item.StaticName;
        //                newFieldChoice.DisplayName = item.Isim;
        //                newFieldChoice.Type = Sharepoint_Copy_WS.FieldType.Choice;
        //                newFieldChoice.Value = controlsNameList[count].Text;
        //                abc.Add(newFieldChoice);

        //                count++;
        //            }
        //        }
        //        else if (controlsNameList[count] is DateTimePicker) {
        //            Sharepoint_Copy_WS.FieldInformation newFieldDate = new Sharepoint_Copy_WS.FieldInformation();
        //            newFieldDate.InternalName = item.StaticName;
        //            newFieldDate.DisplayName = item.Isim;
        //            newFieldDate.Type = Sharepoint_Copy_WS.FieldType.DateTime;
        //            newFieldDate.Value = Convert.ToDateTime(controlsNameList[count].Text).ToString("yyyy-MM-ddTHH:mm:ssZ");
        //            abc.Add(newFieldDate);
        //            count++;
        //        }
        //        else if (controlsNameList[count] is RichTextBox) {
        //            Sharepoint_Copy_WS.FieldInformation newFieldNote = new SPCopy_WS.FieldInformation();
        //            newFieldNote.InternalName = item.StaticName;
        //            newFieldNote.DisplayName = item.Isim;
        //            newFieldNote.Type = Sharepoint_Copy_WS.FieldType.Text;
        //            newFieldNote.Value = controlsNameList[count].Text;
        //            abc.Add(newFieldNote);
        //            count++;
        //        }
        //        else if(controlsNameList[count] is CheckedListBox)
        //        {

        //            CheckedListBox chkList = controlsNameList[count] as CheckedListBox;
        //            Sharepoint_Copy_WS.FieldInformation newField = new SPCopy_WS.FieldInformation();
        //            newField.InternalName = item.StaticName;
        //            newField.DisplayName = item.Isim;
        //            newField.Type = Sharepoint_Copy_WS.FieldType.Lookup;
        //            if(chkList.CheckedItems.Count > 0)
        //            {
        //                lstMultiLineControl.Add(item);
        //                newField.Value = chkList.CheckedItems[0].ToString();
        //                AGC_WebServices.LookupFieldValue[] fieldArr = new LookupFieldValue[chkList.CheckedItems.Count];
        //                for (int i = 0; i < chkList.CheckedItems.Count; i++)
        //                {
        //                    //fieldArr[i] = chkList.CheckedItems[i] as LookupFieldValue;
        //                    LookupFieldValue val = (lookupValues[chkList.Name] as LookupFieldValue[]).Where(a => a.Value == chkList.CheckedItems[i].ToString()).FirstOrDefault();
        //                    if(val != null)
        //                    {
        //                        fieldArr[i] = val;
        //                    }
        //                }
        //                lstLookupFieldValues.Add(fieldArr);

        //            }
        //            else
        //            {
        //                newField.Value = "";
        //            }
        //            abc.Add(newField);
        //            count++;

        //        }
        //        else
        //        {
        //            MessageBox.Show(controlsNameList[count].Name);
        //        }

        //        //else if (controlsNameList[count] is RadioButton) {
        //        //}
        //    }
        //    controlsNameList.Clear();
        //    return abc;

        //}
        #endregion

        private void BtnKullaniciKaydetClick(object sender, EventArgs e)
        {
            //load the xml Document
            XmlDocument xmlDocread = new XmlDocument();
            xmlDocread.Load(Application.StartupPath + "\\scanUpload.xml");

            //new xml Document
            XmlDocument xmlDoc = new XmlDocument();

            if (!chbVarsayilanKullanici.Checked)
            {
                if (chbBilgiKayit.Checked)
                {

                    // Write down the XML declaration
                    XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);

                    // Create the root element
                    XmlElement rootNode = xmlDoc.CreateElement("ScanUpload");
                    xmlDoc.InsertBefore(xmlDeclaration, xmlDoc.DocumentElement);
                    xmlDoc.AppendChild(rootNode);

                    // Create a new element and add it to the root node
                    XmlElement parentNode = xmlDoc.CreateElement("Information");

                    // Set attribute name and value!
                    parentNode.SetAttribute("Url", xmlDocread.DocumentElement["Information"].Attributes["Url"].Value);
                    xmlDoc.DocumentElement.PrependChild(parentNode);

                    //parentNode.SetAttribute("WebName", xmlDocread.DocumentElement["Information"].Attributes["WebName"].Value);
                    //xmlDoc.DocumentElement.PrependChild(parentNode);

                    //parentNode.SetAttribute("ListName", xmlDocread.DocumentElement["Information"].Attributes["ListName"].Value);
                    //xmlDoc.DocumentElement.PrependChild(parentNode);

                    // Create a new element and add it to the root node
                    parentNode = xmlDoc.CreateElement("Credential");

                    // Set attributes name and value!
                    parentNode.SetAttribute("Exist", chbBilgiKayit.Checked.ToString());
                    xmlDoc.DocumentElement.PrependChild(parentNode);
                    parentNode.SetAttribute("UserName", Sifrele(txtKullanici.Text));
                    xmlDoc.DocumentElement.PrependChild(parentNode);
                    parentNode.SetAttribute("Password", Sifrele(txtSifre.Text));
                    xmlDoc.DocumentElement.PrependChild(parentNode);
                    parentNode.SetAttribute("Domain", Sifrele(txtEtkiAlani.Text));
                    xmlDoc.DocumentElement.PrependChild(parentNode);

                    // Save to the XML file
                    xmlDoc.Save(Application.StartupPath + "\\scanUpload.xml");
                }
                else
                {

                    // Write down the XML declaration
                    XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);

                    // Create the root element
                    XmlElement rootNode = xmlDoc.CreateElement("ScanUpload");
                    xmlDoc.InsertBefore(xmlDeclaration, xmlDoc.DocumentElement);
                    xmlDoc.AppendChild(rootNode);

                    // Create a new element and add it to the root node
                    XmlElement parentNode = xmlDoc.CreateElement("Information");

                    // Set attribute name and value!
                    parentNode.SetAttribute("Url", xmlDocread.DocumentElement["Information"].Attributes["Url"].Value);
                    xmlDoc.DocumentElement.PrependChild(parentNode);

                    //parentNode.SetAttribute("WebName", xmlDocread.DocumentElement["Information"].Attributes["WebName"].Value);
                    //xmlDoc.DocumentElement.PrependChild(parentNode);

                    //parentNode.SetAttribute("ListName", xmlDocread.DocumentElement["Information"].Attributes["ListName"].Value);
                    //xmlDoc.DocumentElement.PrependChild(parentNode);

                    // Create a new element and add it to the root node
                    parentNode = xmlDoc.CreateElement("Credential");

                    // Set attributes name and value!
                    parentNode.SetAttribute("Exist", chbBilgiKayit.Checked.ToString());
                    xmlDoc.DocumentElement.PrependChild(parentNode);
                    parentNode.SetAttribute("UserName", xmlDocread.DocumentElement["Credential"].Attributes["UserName"].Value);
                    xmlDoc.DocumentElement.PrependChild(parentNode);
                    parentNode.SetAttribute("Password", xmlDocread.DocumentElement["Credential"].Attributes["Password"].Value);
                    xmlDoc.DocumentElement.PrependChild(parentNode);
                    parentNode.SetAttribute("Domain", xmlDocread.DocumentElement["Credential"].Attributes["Domain"].Value);
                    xmlDoc.DocumentElement.PrependChild(parentNode);

                    // Save to the XML file
                    xmlDoc.Save(Application.StartupPath + "\\scanUpload.xml");
                }
            }
            else
            {
                // Write down the XML declaration
                XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);

                // Create the root element
                XmlElement rootNode = xmlDoc.CreateElement("ScanUpload");
                xmlDoc.InsertBefore(xmlDeclaration, xmlDoc.DocumentElement);
                xmlDoc.AppendChild(rootNode);

                // Create a new element and add it to the root node
                XmlElement parentNode = xmlDoc.CreateElement("Information");

                // Set attribute name and value!
                parentNode.SetAttribute("Url", xmlDocread.DocumentElement["Information"].Attributes["Url"].Value);
                xmlDoc.DocumentElement.PrependChild(parentNode);

                // Create a new element and add it to the root node
                parentNode = xmlDoc.CreateElement("Credential");

                // Set attributes name and value!
                parentNode.SetAttribute("Exist", "False");
                xmlDoc.DocumentElement.PrependChild(parentNode);
                parentNode.SetAttribute("UserName", xmlDocread.DocumentElement["Credential"].Attributes["UserName"].Value);
                xmlDoc.DocumentElement.PrependChild(parentNode);
                parentNode.SetAttribute("Password", xmlDocread.DocumentElement["Credential"].Attributes["Password"].Value);
                xmlDoc.DocumentElement.PrependChild(parentNode);
                parentNode.SetAttribute("Domain", xmlDocread.DocumentElement["Credential"].Attributes["Domain"].Value);
                xmlDoc.DocumentElement.PrependChild(parentNode);

                // Save to the XML file
                xmlDoc.Save(Application.StartupPath + "\\scanUpload.xml");
            }
            if ((MessageBox.Show("Ayarların aktif olabilmesi icin lutfen programı yeniden baslatınız", "Baslatılsınmı", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning)) == DialogResult.Yes)
            {
                this.Close();
            }
        }

        public string RcharDetect(string libraryName)
        {
            if (libraryName != "")
            {
                List<char> yenisi = new List<char>();
                foreach (char item in libraryName.ToCharArray())
                {
                    if (item == 'ö' | item == 'ç' | item == 'ş' | item == 'ı' | item == 'ü' | item == 'ğ' | item == 'İ' | item == 'Ö' | item == 'Ü' | item == 'Ç' | item == 'Ş' | item == 'Ğ')
                    {
                    }
                    else yenisi.Add(item);
                }
                foreach (char nitem in yenisi)
                {
                    relativeLibraryName += nitem;
                }
            }
            return relativeLibraryName;
        }

        #region coklu tarama

        private readonly List<CopyFile> _documentsAdded = new List<CopyFile>();
        public CopyFile ScannedDocument = new CopyFile();
        private string _pdfSonTwain = string.Empty;
        private string _itemNamePdf = string.Empty;

        private void BtnCombineSaveClick(object sender, EventArgs e)
        {
            List<System.Windows.Forms.Control> list = new List<System.Windows.Forms.Control>();
            System.Windows.Forms.Control control;
            System.Windows.Forms.Control controlNext;
            System.Windows.Forms.Control controlBase = grpBoxControls.Controls[0];
            for (int index = 0; index < grpBoxControls.Controls.Count; index++)
            {
                if (index + 2 > grpBoxControls.Controls.Count)
                {
                    control = grpBoxControls.Controls[index];
                    controlNext = controlBase;
                }
                else
                {
                    control = grpBoxControls.Controls[index];
                    controlNext = grpBoxControls.Controls[index + 1];
                }


                control.Focus();
                controlNext.Focus();


                if (!control.CausesValidation)
                {
                    list.Add(control);
                }
            }

            if (list.Count > 0)
            {
                DialogResult = DialogResult.None;
                MessageBox.Show("Lütfen Gerekli Alanları Doldurunuz!");
                //grpBoxControls.Refresh();
                list[0].Focus();
                list.Clear();
            }
            else
            {
                this.Cursor = Cursors.WaitCursor;
                if (upType != null)
                {
                    switch (upType)
                    {
                        case UploadType.Browse:
                            SaveDocToStartupBrowse();
                            break;
                        case UploadType.Scanner:
                            SaveDocToStartup();
                            break;
                        default:
                            MessageBox.Show("Doküman yükleme tipi okunamıyor");
                            return;
                    }
                }

                if (documentsByteList.Count > 0)
                {
                    //#region Prepare Source Files:

                    //List<string> filePaths = new List<string>();

                    //foreach (CopyFile file in _documentsAdded)
                    //{
                    //    filePaths.Add(file.FileSource);
                    //}

                    //#endregion Prepare Source Files...

                    //string fileName = _pdfSonTwain;
                    //outgoingSourceItemId = _pdfSonTwain;

                    //#region Read New Saved File:

                    //byte[] documentBytes = null;
                    //try
                    //{
                    //    documentBytes = File.ReadAllBytes(fileName);
                    //}
                    //catch (Exception ex)
                    //{

                    //}

                    //CopyFile savedFile = new CopyFile()
                    //                         {
                    //                             FileName = Path.GetFileNameWithoutExtension(fileName),
                    //                             FileExt = Path.GetExtension(fileName),
                    //                             FileGUID = Guid.NewGuid(),
                    //                             FileBytes = documentBytes,
                    //                             FileSource = Path.GetFullPath(fileName)
                    //                         };

                    //#endregion Read New Saved File...

                    //ScannedDocument = savedFile;

                    //_documentsAdded.Clear();

                    //DialogResult = DialogResult.OK;

                    uploadProgressBegin();
                    if (upType == UploadType.Scanner)
                        dynamicDotNetTwain.RemoveAllImages();
                    else if (upType == UploadType.Browse)
                        documentsByteList.Clear();


                    //Formu temizlemek için.
                    for (int i = 1; i < grpBoxControls.Controls.Count; i = i + 2)
                    {
                        grpBoxControls.Controls.ClearControls();
                    }
                    btnCombineSave.Enabled = false;
                    this.Cursor = Cursors.Default;
                    pathPanel.Hide();
                    pathPanel.Visible = false;
                    btnBrowse.Enabled = true;
                    doc = null;
                    btnCombineSave.Enabled = false;
                }
                else
                {
                    this.Cursor = Cursors.Default;
                    MessageBox.Show("You didn't scan any documents...", "Error", MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
                    DialogResult = DialogResult.Cancel;
                }
            }

        }

        private bool SaveDocument(string fileName, byte[] fileBytes)
        {
            bool returnState = false;

            try
            {
                FileStream fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write);
                fileStream.Write(fileBytes, 0, fileBytes.Length);
                fileStream.Close();
                returnState = true;
            }
            catch (Exception ex)
            {
                returnState = false;
            }

            return returnState;
        }

        private bool DeleteDocument(string filePath)
        {
            bool returnState = false;

            try
            {
                File.Delete(filePath);

                returnState = true;
            }
            catch (Exception ex)
            {
                returnState = false;
            }

            return returnState;
        }

        
        #endregion

        #region Upload kısımları
        public void uploadProgressBegin()
        {
            bool uploadControl = false;
            bool updateControl = false;
            try
            {
                uploadControl = uploadDocument(oFields);
                copyFields.Clear();
                lblInfo.Text = "Döküman yüklemesi başarılı bir şekilde tamamlandı...";
                if (uploadControl && Methods.LstMultiLineControl.Count > 0)
                {
                    AGC_WebServices.Service myWS = new AGC_WebServices.Service();

                    //muratpcWS.AGC_WebService myWS = new muratpcWS.AGC_WebService();
                    //myWS.Credentials = System.Net.CredentialCache.DefaultCredentials;
                    myWS.Credentials = UserProperty.UserProperties.Credential;

                    //updateControl = myWS.updateLookUpFieldValue(cmbSunucu.SelectedItem.ToString(), outgoingSourceListId, outgoingRelatedFieldName, outgoingSourceItemId, cmbKutuphane.SelectedItem.ToString(), outgoingLookupFieldName, outgoingChoosenOne);
                    updateControl = myWS.UpdateLookUpField(sAdres, sLibraryName, Utility.NewFileNameContainer, Methods.LstMultiLineControl.ToArray(), Methods.LstLookupFieldValues.ToArray());
                    lookUpCounter = 0;
                    Methods.LstLookupFieldValues.Clear();
                    Methods.LstMultiLineControl.Clear();
                    Utility.NewFileNameContainer = "";
                    lookUpFieldInfo.Clear();
                    //lookupValues.Clear();
                    if (!updateControl)
                    {
                        MessageBox.Show("Lutfen alanları kontrol ediniz");
                    }
                }
            }
            catch
            {
                this.Enabled = true;
                uploadMsg = "Dosya Kaydedilirken bir sorunla karşılaşıldı";
                cmbKutuphane.SelectedItem = null;
                cmbIcerikTip.SelectedItem = null;
                this.Cursor = Cursors.Default;
            }
        }


        #endregion

        private void BtnScannerSettingsClick(object sender, EventArgs e)
        {
            Options_FORM optionsForm = new Options_FORM();
            optionsForm.ShowDialog();
            LoadSettings();
        }
        private void ComboLoad()
        {
            cmbOCR.Items.Add("OCR ile PDF Dosyası");
            cmbOCR.Items.Add("PDF Dosyası");
            cmbOCR.Items.Add("OCR ile Text Dosyası");
            cmbOCR.SelectedIndex = 0;
        }
        private void LoadSettings()
        {
            #region old
            //SPROOTSITEURL = Properties.Settings.Default.SPROOTSITEURL;/*0*/
            //ScannerSettingsList.Add(SPROOTSITEURL);

            //SCANDPI_X = Properties.Settings.Default.SCANDPI_X;/*1*/
            //ScannerSettingsList.Add(SCANDPI_X.ToString());

            //SCANDPI_Y = Properties.Settings.Default.SCANDPI_Y;/*2*/
            //ScannerSettingsList.Add(SCANDPI_Y.ToString());

            //SCANWIDTH = Properties.Settings.Default.SCANWIDTH;/*3*/
            //ScannerSettingsList.Add(SCANWIDTH.ToString());

            //SCANHEIGHT = Properties.Settings.Default.SCANHEIGHT;/*4*/
            //ScannerSettingsList.Add(SCANHEIGHT.ToString());

            //SCANCOLORPROFILE = Properties.Settings.Default.SCANCOLORPROFILE;/*5*/
            //ScannerSettingsList.Add(SCANCOLORPROFILE.ToString());

            //SCANBITDEPTH = Properties.Settings.Default.SCANBITDEPTH;/*6*/
            //ScannerSettingsList.Add(SCANBITDEPTH.ToString());

            //SCANCOMBINEMOD_PDF = Properties.Settings.Default.SCANCOMBINEMOD_PDF;/*7*/
            //ScannerSettingsList.Add(SCANCOMBINEMOD_PDF.ToString());

            //DEBUGMODE = Properties.Settings.Default.DEBUGMODE;/*8*/
            //ScannerSettingsList.Add(DEBUGMODE.ToString()); 
            #endregion

        
            this.dynamicDotNetTwain.SetViewMode(1, 1);
            this.dynamicDotNetTwain.AllowMultiSelect = false;
            bHaveScanner = dynamicDotNetTwain.SelectSourceByIndex(0); // source seçimi
            
            #region Scanner Properties
            dynamicDotNetTwain.JPEGQuality = Convert.ToInt16(Properties.Settings.Default.JPpegQuality);
            dynamicDotNetTwain.PDFAuthor = Properties.Settings.Default.PDFAuthor;
            dynamicDotNetTwain.PDFCreator = Properties.Settings.Default.PDFCreator;
            dynamicDotNetTwain.PDFProducer = Properties.Settings.Default.PDFProducer;
            if (Properties.Settings.Default.CapPixelType.ToString() == Dynamsoft.DotNet.TWAIN.Enums.TWICapPixelType.TWPT_BW.ToString())
            {
                dynamicDotNetTwain.PixelType = Dynamsoft.DotNet.TWAIN.Enums.TWICapPixelType.TWPT_BW;
                dynamicDotNetTwain.BitDepth = 1;
            }
            else if(Properties.Settings.Default.CapPixelType.ToString() == Dynamsoft.DotNet.TWAIN.Enums.TWICapPixelType.TWPT_GRAY.ToString())
            {
                dynamicDotNetTwain.PixelType = Dynamsoft.DotNet.TWAIN.Enums.TWICapPixelType.TWPT_GRAY;
                dynamicDotNetTwain.BitDepth = 8;
            }
            else if (Properties.Settings.Default.CapPixelType.ToString() == Dynamsoft.DotNet.TWAIN.Enums.TWICapPixelType.TWPT_RGB.ToString())
            {
                dynamicDotNetTwain.PixelType = Dynamsoft.DotNet.TWAIN.Enums.TWICapPixelType.TWPT_RGB;
                dynamicDotNetTwain.BitDepth = 24;
            }
            if (Properties.Settings.Default.PDFCompressionType.ToString() == Dynamsoft.DotNet.TWAIN.Enums.DWTPDFCompressionType.enumAutoEncode.ToString())
            {
                dynamicDotNetTwain.PDFCompressionType = Dynamsoft.DotNet.TWAIN.Enums.DWTPDFCompressionType.enumAutoEncode;
            }
            else if (Properties.Settings.Default.PDFCompressionType.ToString() == Dynamsoft.DotNet.TWAIN.Enums.DWTPDFCompressionType.enumCCITTFax4Encode.ToString())
            {
                dynamicDotNetTwain.PDFCompressionType = Dynamsoft.DotNet.TWAIN.Enums.DWTPDFCompressionType.enumCCITTFax4Encode;
            }
            else if (Properties.Settings.Default.PDFCompressionType.ToString() == Dynamsoft.DotNet.TWAIN.Enums.DWTPDFCompressionType.enumFlateEncode.ToString())
            {
                dynamicDotNetTwain.PDFCompressionType = Dynamsoft.DotNet.TWAIN.Enums.DWTPDFCompressionType.enumFlateEncode;
            }
            else if (Properties.Settings.Default.PDFCompressionType.ToString() == Dynamsoft.DotNet.TWAIN.Enums.DWTPDFCompressionType.enumJPEGEncode.ToString())
            {
                dynamicDotNetTwain.PDFCompressionType = Dynamsoft.DotNet.TWAIN.Enums.DWTPDFCompressionType.enumJPEGEncode;
            }

            if (Properties.Settings.Default.PDFPageSize == Dynamsoft.DotNet.TWAIN.Enums.DWTPDFPageSize.A3.ToString())
            {
                dynamicDotNetTwain.PDFPageSize = Dynamsoft.DotNet.TWAIN.Enums.DWTPDFPageSize.A3;
            }
            else if(Properties.Settings.Default.PDFPageSize == Dynamsoft.DotNet.TWAIN.Enums.DWTPDFPageSize.A4.ToString())
            {
                dynamicDotNetTwain.PDFPageSize = Dynamsoft.DotNet.TWAIN.Enums.DWTPDFPageSize.A4;
            }
            else if (Properties.Settings.Default.PDFPageSize == Dynamsoft.DotNet.TWAIN.Enums.DWTPDFPageSize.A5.ToString())
            {
                dynamicDotNetTwain.PDFPageSize = Dynamsoft.DotNet.TWAIN.Enums.DWTPDFPageSize.A5;
            }
            dynamicDotNetTwain.Resolution = Convert.ToInt32(Properties.Settings.Default.Resolution);
            

            if (Properties.Settings.Default.TIFFCompressionType == Dynamsoft.DotNet.TWAIN.Enums.DWTTIFFCompressionType.TIFF_AUTO.ToString())
            {
                dynamicDotNetTwain.TIFFCompressionType = Dynamsoft.DotNet.TWAIN.Enums.DWTTIFFCompressionType.TIFF_AUTO;
            }
            else if (Properties.Settings.Default.TIFFCompressionType == Dynamsoft.DotNet.TWAIN.Enums.DWTTIFFCompressionType.TIFF_NONE.ToString())
            {
                dynamicDotNetTwain.TIFFCompressionType = Dynamsoft.DotNet.TWAIN.Enums.DWTTIFFCompressionType.TIFF_NONE;
            }
            else if (Properties.Settings.Default.TIFFCompressionType == Dynamsoft.DotNet.TWAIN.Enums.DWTTIFFCompressionType.TIFF_RLE.ToString())
            {
                dynamicDotNetTwain.TIFFCompressionType = Dynamsoft.DotNet.TWAIN.Enums.DWTTIFFCompressionType.TIFF_RLE;
            }
            dynamicDotNetTwain.IfShowPrintUI = Convert.ToBoolean(Properties.Settings.Default.IfShowPrintUI);
            dynamicDotNetTwain.IfShowUI = Convert.ToBoolean(Properties.Settings.Default.IfShowPrintUI);
            dynamicDotNetTwain.IfFeederEnabled = Convert.ToBoolean(Properties.Settings.Default.UseADF);
            dynamicDotNetTwain.IfAutoFeed = Convert.ToBoolean(Properties.Settings.Default.UseADF);
            dynamicDotNetTwain.IfDuplexEnabled = Convert.ToBoolean(Properties.Settings.Default.IfDuplexScan);
            if (Properties.Settings.Default.Capability == Dynamsoft.DotNet.TWAIN.Enums.TWCapability.ICAP_AUTODISCARDBLANKPAGES.ToString())
                dynamicDotNetTwain.Capability = Dynamsoft.DotNet.TWAIN.Enums.TWCapability.ICAP_AUTODISCARDBLANKPAGES;

            
            #endregion

            //sigleton class
            UserProperty.PrepareUserCredential();
            
            
        }

        #region TWAIN ile alakalı scan code ları
        private void TwainTarama()
        {
            dynamicDotNetTwain.IfAppendImage = true;// sona eklemek icin
            AcquireImage();
        }

        private void AcquireImage()
        {
            dynamicDotNetTwain.SelectSource();
            dynamicDotNetTwain.IfShowUI = false;
            dynamicDotNetTwain.OpenSource();
            dynamicDotNetTwain.IfDisableSourceAfterAcquire = true;

            if (SCANCOLORPROFILE == 0)
            {
                dynamicDotNetTwain.PixelType = Dynamsoft.DotNet.TWAIN.Enums.TWICapPixelType.TWPT_RGB;
            }
            else if (SCANCOLORPROFILE != 0)
            {
                dynamicDotNetTwain.PixelType = Dynamsoft.DotNet.TWAIN.Enums.TWICapPixelType.TWPT_GRAY;
            }
            dynamicDotNetTwain.BitDepth = Convert.ToInt16(SCANBITDEPTH);

            dynamicDotNetTwain.Resolution = (float)Convert.ToInt16(SCANDPI_X);

            dynamicDotNetTwain.IfFeederEnabled = true;
            dynamicDotNetTwain.AcquireImage();
            //dynamicDotNetTwain_OnPreAllTransfers();

        }

        //private void dynamicDotNetTwain_OnPreAllTransfers()
        //{
        //    IfInsertEnable();

        //}

        //private void IfInsertEnable()
        //{
        //    if (dynamicDotNetTwain.HowManyImagesInBuffer == 0)
        //    {
        //        btnCombineSave.Enabled = false;
        //    }
        //    else
        //    {
        //        btnCombineSave.Enabled = true;
        //    }
        //}

        private void SaveDocToStartup()
        {
            string timeNow = DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss");
            List<byte[]> documentBytesList = new List<byte[]>();
             byte[] sbytes = new byte[1];
            try
            {
                bool isOnlyPDF = false;

                string languageFolder = Application.StartupPath + "\\tessdata\\";


                this.dynamicDotNetTwain.OCRTessDataPath = languageFolder;
                this.dynamicDotNetTwain.OCRLanguage = "tur";

                this.dynamicDotNetTwain.OCRResultFormat = Dynamsoft.DotNet.TWAIN.OCR.ResultFormat.PDFImageOverText;
                this.dynamicDotNetTwain.OCRDllPath = Application.StartupPath;
                Dynamsoft.DotNet.TWAIN.IndexList list = new Dynamsoft.DotNet.TWAIN.IndexList();
                for (int i = 0; i < this.dynamicDotNetTwain.HowManyImagesInBuffer; i++)
                {
                    list.Add(i);
                }
                

                if (cmbOCR.SelectedIndex == 0) //PDF Image Over Text
                {
                    dynamicDotNetTwain.OCRResultFormat = Dynamsoft.DotNet.TWAIN.OCR.ResultFormat.PDFImageOverText;
                    SetPDFValueToPDFFile();
                }
                else if (cmbOCR.SelectedIndex == 2) //Text File
                {
                    dynamicDotNetTwain.OCRResultFormat = Dynamsoft.DotNet.TWAIN.OCR.ResultFormat.Text;
                }
                else if (cmbOCR.SelectedIndex == 1)
                {
                    isOnlyPDF = true;
                    SetPDFValueToPDFFile();
                }
                dynamicDotNetTwain.CloseSource();
               
                if (isOnlyPDF)
                {
                    sbytes = this.dynamicDotNetTwain.SaveAllAsPDFToBytes();
                }
                else
                {
                    sbytes = dynamicDotNetTwain.OCR(list);
                }
                dynamicDotNetTwain.RemoveAllImages();
                GC.Collect();

                lblSayfa.Text = "0";
                if (sbytes != null)
                {
                    SaveFileDialog sfd = new SaveFileDialog();
                    BrowseDoc filedlg = new BrowseDoc(ref sfd, sLibraryName, sAdres);
                    string filt = "";
                    if (cmbOCR.SelectedIndex == 0 || cmbOCR.SelectedIndex == 1)
                    {
                        filt = "PDF File(*.pdf)| *.pdf";
                    }
                    else if (cmbOCR.SelectedIndex == 2)
                    {
                        filt = "Txt File (*.txt)| *.txt";
                    }
                    bool result = filedlg.SaveFileDialog(filt, sbytes);
                    if (!result)
                    {
                        MessageBox.Show("Doküman oluşturulamadı.\n Error String = \n" + this.dynamicDotNetTwain.ErrorString, "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }
                else
                {
                    MessageBox.Show("Doküman oluşturulamadı.\n Error String = \n" + this.dynamicDotNetTwain.ErrorString, "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message + "\n" + ex.StackTrace, "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }


            documentBytesList.Add(sbytes);

            //foreach (byte[] documentBytes in documentBytesList)
            //{
            //    if (documentBytes != null)
            //    {
            //        string fileName = DateTime.Now.ToString("yyyyMMdd") + "_" + Guid.NewGuid().ToString() + ".pdf";
            //        _pdfSonTwain = fileName;
            //        if (SaveDocument(fileName, documentBytes))
            //        {
            //            CopyFile file = new CopyFile()
            //            {
            //                FileName = Path.GetFileNameWithoutExtension(fileName),
            //                FileExt = Path.GetExtension(fileName),
            //                FileGUID = Guid.NewGuid(),
            //                FileBytes = documentBytes,
            //                FileSource = Path.GetFullPath(fileName)
            //            };

            //            _documentsAdded.Add(file);
            //        }
            //    }
            //}
        }
        /// <summary>
        /// Sezgin
        /// </summary>
        private void SaveDocToStartupBrowse()
        {
            string timeNow = DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss");

            //documentsByteList.Add(dynamicDotNetTwain.SaveAllAsPDFToBytes()/*dynamicDotNetTwain.SaveImageToBytes(dynamicDotNetTwain.CurrentImageIndexInBuffer, Dynamsoft.DotNet.TWAIN.Enums.DWTImageFileFormat.WEBTW_TIF)*/);

            foreach (byte[] doc in documentsByteList)
            {
                if (doc != null)
                {
                    string fileName = sFileSourcePath;
                    _pdfSonTwain = fileName;
                    if (SaveDocument(fileName, doc))
                    {
                        CopyFile file = new CopyFile()
                        {
                            FileName = Path.GetFileNameWithoutExtension(fileName),
                            FileExt = Path.GetExtension(fileName),
                            FileGUID = Guid.NewGuid(),
                            FileBytes = doc,
                            FileSource = Path.GetFullPath(fileName)
                        };

                        _documentsAdded.Add(file);
                    }
                }
            }
        }
        #endregion

        #region Config ayarlarının degistirilebilmesi icin
        private void LsvAppConfigSelectedIndexChanged(object sender, EventArgs e)
        {
            txtKeys.Text = lsvAppConfig.FocusedItem.SubItems[0].Text;
            txtValues.Text = lsvAppConfig.FocusedItem.SubItems[1].Text;
        }

        private void BtnAddtoConfigClick(object sender, EventArgs e)
        {
            try
            {
                if (txtKeys.Text != "" && txtValues.Text != "")
                {
                    if (MessageBox.Show("Emin misiniz?", "Konfigurasyon ayarları degistiriliyor", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                    {
                        ChangeConfig(Crypt.Encrypt(txtKeys.Text), Crypt.Encrypt(txtValues.Text));
                        if ((MessageBox.Show("Ayarların aktif olabilmesi icin lutfen programı yeniden baslatınız", "Baslatılsınmı", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning)) == DialogResult.Yes)
                        {
                            this.Close();
                        }
                    }
                }
                else
                    MessageBox.Show("Kaydederken hata olustu!");
            }
            catch (Exception ex)
            {

            }
        }

        public void ChangeConfig(string keyValue, string newValue)
        {
            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(AppDomain.CurrentDomain.BaseDirectory + "..\\..\\App.config");
                XmlNode appSettingsNode = xmlDoc.SelectSingleNode("configuration/appSettings");
                foreach (XmlNode childNode in appSettingsNode)
                {
                    if (childNode.Attributes["key"].Value == keyValue)
                    {
                        childNode.Attributes["value"].Value = newValue;
                        MessageBox.Show("Konfigurasyon ayarları guncellendi!!");
                    }
                    xmlDoc.Save(AppDomain.CurrentDomain.BaseDirectory + "..\\..\\App.config");
                    xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
                    lsvAppConfig.Update();

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Islem basarısız!!! " + ex.Message);
            }
        }

        private void TabControlArsivSelectedIndexChanged(object sender, EventArgs e)
        {
            tabControlArsiv.SelectedIndexChanged -= TabControlArsivSelectedIndexChanged;
            if (tabControlArsiv.SelectedIndex == 2)
            {
                tabControlArsiv.SelectedIndex = 0;
                frmPassword f2 = new frmPassword();
                //if (f2.ShowDialog() == DialogResult.OK)
                //{
                //    tabControlArsiv.SelectedIndex = 2;
                //}
                //else
                //    tabControlArsiv.SelectedIndex = 0;
                tabControlArsiv.SelectedIndex = 2;
            }
            tabControlArsiv.SelectedIndexChanged += TabControlArsivSelectedIndexChanged;
        }
        #endregion

        private void BtnBrowseClick(object sender, EventArgs e)
        {
            upType = UploadType.Browse;
            using (BrowseDoc ofd = new BrowseDoc(ref openFileDialog1, sLibraryName, sAdres))
            {
                doc = ofd.OpenDialog();

                if (doc != null)
                {
                    pathPanel.Visible = true;
                    documentsByteList.Add(doc);
                    sFileSourcePath = ofd.SavePath;
                    CreatePanel(sFileSourcePath);
                    pathPanel.Show();

                    //removePathLinkLbl.Text = "x";
                    //removePathLinkLbl.Location = new Point(pdfPathLabel.Location.X + pdfPathLabel.Size.Width + 5, pdfPathLabel.Location.Y);
                    //removePathLinkLbl.LinkClicked += new LinkLabelLinkClickedEventHandler(RemoveLinkLabelClicked);
                    //pdfPathLabel.LinkClicked += (sSender, sE) => LinkLabel1LinkClicked(sSender, sE, sFileSourcePath);
                    //tpTarama.Controls.Add(removePathLinkLbl);
                    btnTaraGonder.Enabled = false;
                    btnCombineSave.Enabled = true;
                    btnBrowse.Enabled = false;
                }
            }
        }
        private void CreatePanel(string path)
        {
            pdfPathLabel.Text = path;
            pdfPathLabel.LinkClicked += (sender, e) => LinkLabel1LinkClicked(sender, e, sFileSourcePath);
            Button removeButton = new Button();
            Image image = new Bitmap("C:\\Users\\alenoz\\Desktop\\KALE_Scanning\\ico\\1351768592_cancel_48.bmp");
            removeButton.Size = new Size(30, 30);
            removeButton.BackColor = Color.White;
            removeButton.Image = image;
            removeButton.FlatStyle = 0;
            removeButton.FlatAppearance.BorderSize = 0;
            int pdfPathLabelSize = pdfPathLabel.Location.X + pdfPathLabel.Size.Width;
            removeButton.Location = new Point(pdfPathLabelSize + 5, pdfPathLabel.Location.Y - 8);

            removeButton.Click += new EventHandler(RemovePath);
            pathPanel.Controls.Add(removeButton);

        }

        private void RemovePath(object sender, EventArgs e)
        {
            pathPanel.Visible = false;
            btnBrowse.Enabled = true;
            doc = null;
            btnCombineSave.Enabled = false;
        }

        private void LinkLabel1LinkClicked(object sender, LinkLabelLinkClickedEventArgs e, string link)
        {
            System.Diagnostics.Process.Start(link);
        }


    }

}


        private void btnPDFValues_Click(object sender, EventArgs e)
        {
            using (frmPDFValues val = new frmPDFValues())
            {
                DialogResult res = val.ShowDialog();
                if (res == System.Windows.Forms.DialogResult.OK)
                {
                    if (!UserProperty.PDFValue.IsClear)
                    {
                        btnPDFValues.Text = "PDF Bilgileri (*)";
                    }
                    else
                        btnPDFValues.Text = "PDF Bilgileri";
                }
                else if (res == System.Windows.Forms.DialogResult.Abort)
                {
                    btnPDFValues.Text = "PDF Bilgileri";
                }
            }
        }

        private void dynamicDotNetTwain_OnPreAllTransfers_1()
        {
            //IfInsertEnable();
            dynamicDotNetTwain.CloseSource();
            dynamicDotNetTwain.CloseSourceManager();
            dynamicDotNetTwain.UseWaitCursor = false;
            pnlOCR.Show();
        }
        int pageCount = 0;
        private void dynamicDotNetTwain_OnPreTransfer()
        {
            lblSayfa.Text = (dynamicDotNetTwain.HowManyImagesInBuffer + 1 + pageCount).ToString();
        }

        private void btnClearScannedDocuments_Click(object sender, EventArgs e)
        {
            if(MessageBox.Show("Taranmış tüm sayfalar temizlenecektir. Devam edilsin mi ?","Dikkat", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                dynamicDotNetTwain.UseWaitCursor = true;
                dynamicDotNetTwain.RemoveAllImages();
                GC.Collect();
                dynamicDotNetTwain.UseWaitCursor = false;
                pnlOCR.Hide();
                btnTaraGonder.Enabled = true;
                btnBrowse.Enabled = true;
                btnCombineSave.Enabled = false;
            }
        }

        private void btnSelectedPageDelete_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Seçili sayfa listeden kaldırılacaktır. Devam edilsin mi ?", "Dikkat", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                dynamicDotNetTwain.UseWaitCursor = true;
                dynamicDotNetTwain.RemoveImage(dynamicDotNetTwain.CurrentImageIndexInBuffer);
                dynamicDotNetTwain.UseWaitCursor = false;
            }
        }
        private void dynamicDotNetTwain_OnMouseClick(short sImageIndex)
        {
            if (sImageIndex >= 0)
            {
                dynamicDotNetTwain.CurrentImageIndexInBuffer = sImageIndex;
                lblSelectedPage.Text = sImageIndex.ToString();
                btnSelectedPageDelete.Enabled = true;
            }
            else
            {
                btnSelectedPageDelete.Enabled = false;
            }
        }

        private void btnLeft_Click(object sender, EventArgs e)
        {
            dynamicDotNetTwain.RotateLeft(dynamicDotNetTwain.CurrentImageIndexInBuffer);
        }

        private void btnRight_Click(object sender, EventArgs e)
        {
            dynamicDotNetTwain.RotateRight(dynamicDotNetTwain.CurrentImageIndexInBuffer);
        }

        private void btnFlip_Click(object sender, EventArgs e)
        {
            dynamicDotNetTwain.Flip(dynamicDotNetTwain.CurrentImageIndexInBuffer);
        }

        private void btnMirror_Click(object sender, EventArgs e)
        {
            dynamicDotNetTwain.Mirror(dynamicDotNetTwain.CurrentImageIndexInBuffer);
        }

        private void btnFarkliKaydet_Click(object sender, EventArgs e)
        {
            try
            {
                bool isOnlyPDF = false;
               
                string languageFolder = Application.StartupPath +"\\tessdata\\";
            

                this.dynamicDotNetTwain.OCRTessDataPath = languageFolder;
                this.dynamicDotNetTwain.OCRLanguage = "tur";

                this.dynamicDotNetTwain.OCRResultFormat = Dynamsoft.DotNet.TWAIN.OCR.ResultFormat.PDFImageOverText;
                this.dynamicDotNetTwain.OCRDllPath = Application.StartupPath;
                Dynamsoft.DotNet.TWAIN.IndexList list = new Dynamsoft.DotNet.TWAIN.IndexList();
                for (int i = 0; i < this.dynamicDotNetTwain.HowManyImagesInBuffer; i++)
                {
                    list.Add(i);
                }

                
                if (cmbOCR.SelectedIndex == 0) //PDF Image Over Text
                {
                    dynamicDotNetTwain.OCRResultFormat = Dynamsoft.DotNet.TWAIN.OCR.ResultFormat.PDFImageOverText;
                }
                else if (cmbOCR.SelectedIndex == 2)
                {
                    dynamicDotNetTwain.OCRResultFormat = Dynamsoft.DotNet.TWAIN.OCR.ResultFormat.Text;
                }
                else if (cmbOCR.SelectedIndex == 1)
                {
                    isOnlyPDF = true;
                }
                dynamicDotNetTwain.CloseSource();
                byte[] sbytes = new byte[1];
                if (isOnlyPDF)
                {
                    sbytes = this.dynamicDotNetTwain.SaveAllAsPDFToBytes();
                }
                else
                {
                    sbytes = dynamicDotNetTwain.OCR(list);
                }
                dynamicDotNetTwain.RemoveAllImages();
                GC.Collect();

                lblSayfa.Text = "0";
                if (sbytes != null)
                {
                    SaveFileDialog filedlg = new SaveFileDialog();
                    if (cmbOCR.SelectedIndex == 0 || cmbOCR.SelectedIndex == 1)
                    {
                        filedlg.Filter = "PDF File(*.pdf)| *.pdf";
                    }
                    else if (cmbOCR.SelectedIndex == 2)
                    {
                        filedlg.Filter = "Txt File (*.txt)| *.txt";
                    }
                    if (filedlg.ShowDialog() == DialogResult.OK)
                    {
                        FileStream fs = File.OpenWrite(filedlg.FileName);
                        fs.Write(sbytes, 0, sbytes.Length);
                        fs.Close();
                    }
                }
                else
                {
                    MessageBox.Show("Doküman oluşturulamadı.\n Error String = \n" + this.dynamicDotNetTwain.ErrorString,"Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message + "\n" + ex.StackTrace,"Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnGoruntule_Click(object sender, EventArgs e)
        {
            try
            {

                Dynamsoft.DotNet.TWAIN.IndexList list = new Dynamsoft.DotNet.TWAIN.IndexList();
                for (int i = 0; i < this.dynamicDotNetTwain.HowManyImagesInBuffer; i++)
                {
                    list.Add(i);
                }

                dynamicDotNetTwain.CloseSource();
                byte[] sbytes = this.dynamicDotNetTwain.SaveAllAsPDFToBytes();
                dynamicDotNetTwain.RemoveAllImages();
                GC.Collect();

                lblSayfa.Text = "0";
                string tempfileName = Path.ChangeExtension(Path.GetTempFileName(), "pdf");
               
                
                if (sbytes != null && tempfileName != string.Empty)
                {
                   
                    FileStream fs = File.OpenWrite(tempfileName);
                    fs.Write(sbytes, 0, sbytes.Length);
                    fs.Close();
                    Process.Start(tempfileName);
                    
                }
                else
                {
                    MessageBox.Show(this.dynamicDotNetTwain.ErrorString);
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message + "\n" + ex.StackTrace);
            }
        }


        private void SetPDFValueToPDFFile()
        {
            if (!UserProperty.PDFValue.IsClear)
            {
                dynamicDotNetTwain.PDFTitle = UserProperty.PDFValue.Title;
                dynamicDotNetTwain.PDFKeywords = UserProperty.PDFValue.Keywords;
                dynamicDotNetTwain.PDFSubject = UserProperty.PDFValue.Subject;
            }

        }
      


    }

}

       